// Add history
// Generate JSON object from files
// PHP to grab a list of valid files from a directory
// FileSystem revamp
// update the pwd prompt
// Add ls cat etc..

function pathFilename(path) {
    var match = /\/([^\/]+)$/.exec(path);
    if (match) {
	return match[1];
    }
}

function getRandomInt(min, max) {
    // via https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Math/random#Examples
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


function randomChoice(items) {
    return items[getRandomInt(0, items.length-1)];
}


//SUDO
TerminalShell.commands['sudo'] = function(terminal) {
    var cmd_args = Array.prototype.slice.call(arguments);
    cmd_args.shift(); // terminal
    if (cmd_args.join(' ') == 'make me a sandwich') {
	terminal.print('Okay.');
    } else {
	var cmd_name = cmd_args.shift();
	cmd_args.unshift(terminal);
	cmd_args.push('sudo');
	if (TerminalShell.commands.hasOwnProperty(cmd_name)) {
	    this.sudo = true;
	    this.commands[cmd_name].apply(this, cmd_args);
	    delete this.sudo;
	} else if (!cmd_name) {
	    terminal.print('sudo what?');
	} else {
	    terminal.print('sudo: '+cmd_name+': command not found');
	}
    }

    //terminal.print('sudo not available at this time');
};

//Repeat last command
TerminalShell.filters.push(function (terminal, cmd) {
    if (/!!/.test(cmd)) {
	var newCommand = cmd.replace('!!', this.lastCommand);
	terminal.print(newCommand);
	return newCommand;
    } else {
	return cmd;
    }
});

TerminalShell.commands['shutdown'] = function(terminal) {
    if (this.sudo) {
	terminal.print('Broadcast message from guest@n0l3ptr');
	terminal.print();
	terminal.print('The system is going down for maintenance NOW!');
	return $('#screen').fadeOut();
    } else {
	terminal.print('Must be root.');
    }
};

TerminalShell.commands['logout'] =
    TerminalShell.commands['exit'] = 
    TerminalShell.commands['quit'] = function(terminal) {
	terminal.print('Bye.');
	$('#prompt, #cursor').hide();
	terminal.promptActive = false;
    };

//UNKNOWN

function linkFile(url) {
    return {type:'dir', enter:function() {
	window.location = url;
    }};
}
//Script to populate this; not PHP
Filesystem = {
    'welcome.txt': {type:'file', read:function(terminal) {
	terminal.print($('<h4>').text('Welcome to the n0l3ptr console.'));
	terminal.print('This console is based off of unixkcd. It\' still a WIP.');
	terminal.print('Use "ls", "cat", and "cd" to navigate the filesystem.');
    }},
    'license.txt': {type:'file', read:function(terminal) {
	terminal.print($('<p>').html('Client-side logic for Wordpress CLI theme :: <a href="http://thrind.xamai.ca/">R. McFarland, 2006, 2007, 2008</a>'));
	terminal.print($('<p>').html('jQuery rewrite and overhaul :: <a href="http://www.chromakode.com/">Chromakode, 2010</a>'));
	terminal.print();
	$.each([
	    'This program is free software; you can redistribute it and/or',
	    'modify it under the terms of the GNU General Public License',
	    'as published by the Free Software Foundation; either version 2',
	    'of the License, or (at your option) any later version.',
	    '',
	    'This program is distributed in the hope that it will be useful,',
	    'but WITHOUT ANY WARRANTY; without even the implied warranty of',
	    'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the',
	    'GNU General Public License for more details.',
	    '',
	    'You should have received a copy of the GNU General Public License',
	    'along with this program; if not, write to the Free Software',
	    'Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.'
	], function(num, line) {
	    terminal.print(line);
	});
    }}
};

Filesystem['blog'] = linkFile('#');
Filesystem['forums'] = linkFile('#');
Filesystem['about'] = linkFile('#');

TerminalShell.pwd = Filesystem;
var currpwd = '';

//Change this functionality to navigate the filesystem
TerminalShell.commands['cd'] = function(terminal, path) {
    if(path != '../' && path != '..')
    {
	$.get('live_fs/'+currpwd+'listing.html?'+(new Date()), function(data){
	 //check if folder is in our listing.html
	 if(data.indexOf(path+'/') >= 0){
	     currpwd = currpwd + path + '/'
	 }
	 //if its not
	 else{
	     terminal.print('cd: '+path+': No such directory');
	 }
     });
    }
    else if(path == '../' || path == '..')
    {
	currpwd = currpwd.substring(0, currpwd.lastIndexOf("/"));
	currpwd = currpwd.substring(0, currpwd.lastIndexOf("/") + 1);
    }
    else
    {

    }
};


TerminalShell.commands['ls'] = function(terminal, dirpath) {
    $.get('live_fs/'+currpwd+'listing.html?'+(new Date()), function(data){
	terminal.print($(data));
    });
};
TerminalShell.commands['pwd'] = function(terminal, dirpath) {
    terminal.print('/' + currpwd);
    this.pwd = currpwd;
};

TerminalShell.commands['cat'] = function(terminal, path) {
    $.get('live_fs/'+currpwd+'listing.html?'+(new Date()), function(data){
	//check if file is in our listing.html
	if(data.indexOf(path) >= 0)
	{
	    $.get('live_fs/' +currpwd+ path, function(filedata){
		terminal.print(filedata);
	    });
	}
	//if its not
	else{
	    terminal.print('cat: '+path+': No such file or directory');
	}
    });
};

TerminalShell.commands['rm'] = function(terminal, flags, path) {
    if (flags && flags[0] != '-') {
	path = flags;
    }
    if (!path) {
	terminal.print('rm: missing operand');
    } else if (path in this.pwd) {
	if (this.pwd[path].type == 'file') {
	    delete this.pwd[path];
	} else if (this.pwd[path].type == 'dir') {
	    if (/r/.test(flags)) {
		delete this.pwd[path];
	    } else {
		terminal.print('rm: cannot remove '+path+': Is a directory');
	    }
	}
    } else if (flags == '-rf' && path == '/') {
	if (this.sudo) {
	    TerminalShell.commands = {};
	} else {
	    terminal.print('rm: cannot remove /: Permission denied');
	}
    }
};

//Creates nolepointer channel
TerminalShell.commands['write'] =
    function(terminal, nick) {
	if (nick) {
	    $('.irc').slideUp('fast', function() {
		$(this).remove();
	    });
	    var url = "http://widget.mibbit.com/?server=irc.foonetic.net&channel=%23n0l3ptr";
	    if (nick) {
		url += "&nick=" + encodeURIComponent(nick);
	    }
	    TerminalShell.commands['curl'](terminal, url).addClass('irc');
	} else {
	    terminal.print('usage: write <nick>');
	}
    };


function oneLiner(terminal, msg, msgmap) {
    if (msgmap.hasOwnProperty(msg)) {
	terminal.print(msgmap[msg]);
	return true;
    } else {
	return false;
    }
}

TerminalShell.commands['man'] = function(terminal, what) {
    pages = {
	'last': 'Man, last night was AWESOME.',
	'help': 'Man, help me out here.',
	'next': 'Request confirmed; you will be reincarnated as a man next.',
	'cat':  'You are now riding a half-man half-cat.',
	'man': ';o',
	'woman': ';)'
    };
    if (!oneLiner(terminal, what, pages)) {
	terminal.print('Oh, I\'m sure you can figure it out.');
    }
};

//Commands which require no interactivity
TerminalShell.fallback = function(terminal, cmd) {
    oneliners = {
/*	'make me a sandwich': 'What? Make it yourself.',
	'make love': 'I put on my robe and wizard hat.',
	'i read the source code': '<3',
	'pwd': 'You are in a maze of twisty passages, all alike.',
	'lpr': 'PC LOAD LETTER',
	'hello joshua': 'How about a nice game of Global Thermonuclear War?',
	'xyzzy': 'Nothing happens.',
	'date': 'March 32nd',
	'hello': 'Why hello there!',
	'who': 'Doctor Who?',
	'xkcd': 'Yes?',
	'su': 'God mode activated. Remember, with great power comes great ... aw, screw it, go have fun.',
	'fuck': 'I have a headache.',
	'whoami': 'You are Richard Stallman.',
	'nano': 'Seriously? Why don\'t you just use Notepad.exe? Or MS Paint?',
	'top': 'It\'s up there --^',
	'moo':'moo',
	'ping': 'There is another submarine three miles ahead, bearing 225, forty fathoms down.',
	'find': 'What do you want to find? Kitten would be nice.',
	'hello':'Hello.','more':'Oh, yes! More! More!',
	'your gay': 'Keep your hands off it!',
	'hi':'Hi.','echo': 'Echo ... echo ... echo ...',
	'bash': 'You bash your head against the wall. It\'s not very effective.','ssh': 'ssh, this is a library.',
	'uname': 'Illudium Q-36 Explosive Space Modulator',
	'finger': 'Mmmmmm...',
	'kill': 'Terminator deployed to 1984.',
	'use the force luke': 'I believe you mean source.',
	'use the source luke': 'I\'m not luke, you\'re luke!',
	'serenity': 'You can\'t take the sky from me.',
	'enable time travel': 'TARDIS error: Time Lord missing.',
	'ed': 'You are not a diety.'*/
    };

    oneliners['emacs'] = 'You should really use vim.';
    oneliners['vi'] = oneliners['vim'] = 'You should really use emacs.';
};

//Javascript Chatroom
$(document).ready(function() {
    Terminal.promptActive = false;
    function noData() {
	Terminal.print($('<p>').addClass('error').text('Unable to load startup data. :-('));
	Terminal.promptActive = true;
    }
    function startDisplay(){
	Terminal.print('        ___  _ _____       _        ');
	Terminal.print(' _ __  / _ \\| |___ / _ __ | |_ _ __ ');
	Terminal.print('| \'_ \\| | | | | |_ \\| \'_ \\| __| \'__|');
	Terminal.print('| | | | |_| | |___) | |_) | |_| |  '); 
	Terminal.print('|_| |_|\\___/|_|____/| .__/ \\__|_|');   
	Terminal.print('                    |_|       ');
	Terminal.print('');
	Terminal.print('   ****************************************************');
	Terminal.print('   | Welcome to the Florida State University Computer |');
	Terminal.print('   | Security Club website. Make yourself at home, or |');
	Terminal.print('   | if you\'re not comfortable using a command-line   |');
	Terminal.print('   | interface, go to index2.html.                    |');
	Terminal.print('   |                                                  |');
	Terminal.print('   | (For best results, run in full-screen [F-11])    |');
	Terminal.print('   ****************************************************');
	Terminal.print('');
    }
    //FUTURE: Display intro video command

    //This is the loading section
    $('#screen').bind('cli-load', function(e) {
	startDisplay();
	Terminal.promptActive = true;	
    });
    
});
